package com.jxc.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
public class PageController {
	@GetMapping("/{page}")
	public String buildBill(@PathVariable("page")String page) {
		if(StringUtils.isEmpty(page)) {
			return "index";
		}
		return page;
	}
	
	@PostMapping("/login")
	@ResponseBody
	public Object login(String json) {
		return null;
	}
	
	@RequestMapping("/tmp/{page}")
	public void downLoad(@PathVariable("page")String page,
			HttpServletRequest request,HttpServletResponse response) {
		try {
			File dir = new File(ResourceUtils.getURL("classpath:").getPath());
			String jarParent = dir.getParentFile().getParentFile().getParentFile().getPath().replace("file:", "");
			File tag = new File(jarParent+"/tmp/"+page+".xls");
			
			response.setContentType("application/x-msdownload");
			//文件大小
			response.setContentLength((int) tag.length());	
			//文件名
			response.setHeader("Content-Disposition", "attachment;filename=" + new String(page.getBytes(), "iso-8859-1")+".xls");
			OutputStream os = response.getOutputStream();
			FileInputStream stream=new FileInputStream(tag);
			byte data[]=new byte[4096];
			int size=0;
			while((size = stream.read(data))!=-1) {
				os.write(data,0,size);
			}
			os.flush();
			os.close();
			stream.close();
		} catch (FileNotFoundException e) {
			log.error("文件查找不到",e);
		} catch (IOException e) {
			log.error("写入文件",e);
		}
	}
}
